<template>
  <div class="page-container">
    <el-card>
      <VCategory />
    </el-card>

    <el-card class="attr-list" v-show="isShowList">
      <el-row>
        <el-col :span="24">
          <el-button type="primary" :icon="Plus" :disabled="!category3Id" @click="addAttrFrom"
            >添加属性</el-button
          >
        </el-col>
      </el-row>

      <el-table :data="attrList" style="width: 100%" border stripe>
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="attrName" label="属性名称" width="180" />
        <el-table-column label="属性值名称列表">
          <template #default="{ row }">
            <el-tag type="success" v-for="item in row.attrValueList" :key="item.id">
              {{ item.valueName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button size="small" type="warning" :icon="Edit" @click="editAttr(row)" />
            <el-button size="small" type="danger" :icon="Delete" @click="delAttr(row)" />
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-card class="box-card" v-show="!isShowList">
      <div class="text item">
        <el-form label-width="60px" :inline="true" :model="addEditData">
          <el-form-item label="用户名">
            <el-input
              class="addAttrName"
              placeholder="请输入用户名"
              v-model="addEditData.attrName"
            /> </el-form-item
          ><br />
          <el-form-item>
            <el-button type="primary" @click="addAttrName" :disabled="!addEditData.attrName"
              >添加属性值</el-button
            >
            <el-button>取&emsp;消</el-button>
          </el-form-item>
        </el-form>
        <el-table border :data="addEditData.attrValueList" style="width: 100%">
          <el-table-column type="index" label="序号" width="180" />
          <el-table-column prop="valueName" label="属性值名称">
            <template #default="{ row, $index }">
              <el-input
                ref="inputRef"
                v-model="row.valueName"
                v-if="row.isEdit"
                @blur="toSpan(row, $index)"
                @keyup.enter="toSpan(row, $index)"
              />
              <span class="value_span" v-else @click="toInput(row)">{{ row.valueName }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="address" label="操作" width="180">
            <template #default="{ row, $index }">
              <el-popconfirm
                :title="`您确定删除 ${row.valueName} 吗?`"
                @confirm="handelConfirm($index)"
              >
                <template #reference>
                  <el-button :icon="Delete" size="small" type="danger"></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-form label-width="120px" :inline="true">
          <el-form-item>
            <el-button
              type="primary"
              @click="saveAttr"
              :disabled="!addEditData.attrValueList.length"
              >保&emsp;存</el-button
            >
            <el-button @click="handecancel">取&emsp;消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { useCategoryStore } from '@/stores/category'
import { storeToRefs } from 'pinia'
import type {
  resAttrValueList,
  ReqApifoxModel,
  ReqAttrValueList,
  resAttrValueListData
} from '@/types/attr'
import { ref, watch, nextTick } from 'vue'
import { reqGetAttrList, reqAddEditAttr, reqDeleteAttr } from '@/api/Attr'
import { ElMessage, ElMessageBox, type InputInstance } from 'element-plus'

const categoryStore = useCategoryStore()
const { category1Id, category2Id, category3Id } = storeToRefs(categoryStore)

const attrList = ref<resAttrValueList[]>([])
const addEditData = ref<ReqApifoxModel>({
  attrName: '', //属性名
  attrValueList: [], //属性值列表
  categoryId: '', //分类 id
  categoryLevel: 3 //分类等级
})
//店家编辑按钮
const editAttr = (row: resAttrValueList) => {
  // console.log(row)

  isShowList.value = false
  addEditData.value = row
}

const inputRef = ref<InputInstance | null>(null)
//控制列表的隐藏和展示
const isShowList = ref(true)
//点击添加按钮
const addAttrFrom = () => {
  isShowList.value = false
  addEditData.value.categoryId = category3Id.value
}
//删除属性数据
const delAttr = (row: resAttrValueListData) => {
  ElMessageBox.confirm('是否删除该属性?', '删除提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const res = await reqDeleteAttr(row.id)
      if (res.code === 200) {
        ElMessage.success('删除成功')
        //重新请求数据
        getAttrList()
      }
    })
    .catch(() => {
      ElMessage.info('取消删除')
    })
}

//删除添加属性值数据
const handelConfirm = (index: number) => {
  addEditData.value.attrValueList.splice(index, 1)
}

//保存
const saveAttr = async () => {
  const { attrName, attrValueList, id } = addEditData.value
  if (attrName.trim() === '') {
    ElMessage.closeAll()
    ElMessage.error('请输入属性名')
    return
  }
  if (!attrValueList.length) {
    ElMessage.closeAll()
    ElMessage.error('请输入属性值')
    return
  }
  // console.log(addEditData.value)
  const res = await reqAddEditAttr(addEditData.value)

  if (res.code === 200) {
    ElMessage.success(id ? '编辑成功' : '添加成功')
    isShowList.value = true
    getAttrList()
  }

  handecancel()
}

//新增修改弹窗的取消按钮
const handecancel = () => {
  addEditData.value.attrName = ''
  addEditData.value.attrValueList = []
  addEditData.value.categoryId = ''
  addEditData.value.id = ''
}

const addAttrName = () => {
  addEditData.value.attrValueList.push({
    valueName: '',
    isEdit: true
  })

  // DOM 更新是异步的
  // 数据更新以后，并不会立即生效
  // Vue 会将数据先放到一个异步队列中
  // 这时候如果执行了 DOM 操作
  // 因为 input 输入框还没有，所以聚焦效果会没用
  // 需要等待 input 输入框展示，展示以后添加聚焦效果
  // 因此需要使用 nextTick()
  nextTick(() => {
    inputRef.value?.focus()
  })
}

const toSpan = (row: ReqAttrValueList, index: number) => {
  //判断是否是重复
  const isRepeat = addEditData.value.attrValueList.some((item) => {
    if (item !== row) {
      return item.valueName === row.valueName
    }
  })

  if (row.valueName?.trim() === '' || isRepeat) {
    ElMessage.closeAll()
    ElMessage({
      type: 'error',
      message: isRepeat ? '属性值不能重复' : '属性值不能为空也'
    })
    addEditData.value.attrValueList.splice(index, 1)
    return
  }
  row.isEdit = false
}

const toInput = (row: ReqAttrValueList) => {
  row.isEdit = true
  nextTick(() => {
    inputRef.value?.focus()
  })
}

//获取属性列表
const getAttrList = async () => {
  const params = {
    category1Id: category1Id.value,
    category2Id: category2Id.value,
    category3Id: category3Id.value
  }

  const res = await reqGetAttrList(params)
  if (res.code === 200) {
    attrList.value = res.data
  }
}

watch(
  category3Id,
  (newVal) => {
    if (!newVal) {
      // 如果三级分类 id 没有值，是空字符串，需要将属性列表重置为空
      attrList.value = []
    } else {
      // 如果三级分类 id 有值，获取属性列表
      getAttrList()
    }
  },
  {
    immediate: true
  }
)
</script>

<script lang="ts">
export default {
  name: 'VAttr'
}
</script>

<style lang="scss" scoped>
.attr-list,
.el-table {
  margin-top: 20px;
}

.el-tag {
  margin: 5px;
}
.addAttrName {
  width: 250px;
}
.value_span {
  display: block;
}
</style>
